<?php
namespace app\admin\library;

use  cubox\Controller;
use  app\admin\library\User;
use  cubox\Cubox;
use  cubox\Template;
use  cubox\provider\template\Asset;
use  cubox\provider\Url;


class AdminController extends Controller{
    public string|array $pageTitle = '';
    public string $pageIcon  = '';

    public function __construct()
    {
        parent::__construct();
        
        ini_set("session.cookie_httponly", 1);
        session_start();

        if (session_status()!=PHP_SESSION_ACTIVE){
            throw new \Exception("Session not started");
        }
        
        if (!User::isLogin()){
            //if ($this->isAjax()){
            //   echo json_encode(['status'=>'logout','message'=>'未登陆','data'=>[]]);
            //}else{

                //获取当前URL
                $url = Url::base64Encode($_SERVER['REQUEST_URI'],true);
                Cubox::go(Cubox::url('admin','outside','login',['nav'=>$url]));
            //}
        }

        $cache = Cubox::cache();
        Asset::$fileList =  json_decode($cache->get('admin:asset_list')??'[]',true)??[];
    }

    public function __destruct()
    {
        $cache = Cubox::cache();
        $cache->set('admin:asset_list',json_encode(Asset::$fileList));
    }
    /**
     * 显示模板
     * 
     * @param string $name
     * @return void
     */
    public function display(string $name=''){
        if ($name=="") {
            $name  = strtolower($this->name).'_'.$this->action;
        }
        
        $data = $this->getPageData();
        $data['NAME'] = $name;
        //显示frame
        $path = dirname(dirname(__FILE__)).DS.'template'.DS.'frame.html';
         
        $template = new Template($path,$data);
        $template->setPlugApp(User::app());
        return $template->getHtml();
    }


    /**
     * 显示模板
     * 
     * @param string $name
     * @return void
     */
    public function displayBlank(string $name=''){
        if ($name=="") {
            $name  = strtolower($this->name).'_'.$this->action;
        }

        
        $data = $this->getPageData();
        $data['NAME'] = $name;
        //显示frame
        $path = dirname(dirname(__FILE__)).DS.'template'.DS.'blank.html';
         
        $template = new Template($path,$data);
        $template->setPlugApp(User::app());
        return $template->getHtml();
    }
    /**
     * 获取页面数据
     * @return array
     */
    protected function getPageData(){
        $data  = $this->data;
        
        if (is_array($this->pageTitle)){
            $data['__pageTitle'] = implode(' - ',array_reverse( $this->pageTitle));
        }else{
            $data['__pageTitle'] = $this->pageTitle;
        }

        $data['__headerTitle'] = $this->pageTitle;
        $data['__headerIcon'] = $this->pageIcon;
        $data['__siteTitle'] = Cubox::config('system')->admin_title?? Cubox::$title . ' ' . Cubox::$version;
        $data['__appTitle']  = $this->app->title;
        $data['__appIcon']  = $this->app->icon;
        $data['__appName'] = $this->app->name;
        $data['__controllerName'] =  $this->name;
        $data['__actionName'] =  $this->action;


        $userFrontData = User::getFrontData();
        
        if ($userFrontData['photo']==''){
            $userFrontData['photo'] = $this->assetUrl(ROOT.DS.APP.'/admin/assets/image/avatar.png');
        }else{
            $userFrontData['photo'] = Upload::url($userFrontData['photo']);
        }
        $data['__user'] =  $userFrontData;
        $data['__appAlias'] = Cubox::config('alias')->toArray();
        return $data;
    }

    /**
     * 记录日志
     * 
     * @param string $title
     * @param array $content
     */
    protected function log(string $title,array $content = array()){

        $log = Cubox::app('admin')->model('UserLog');
        $data['user_id'] =  User::get('user_id');
        $data['username'] =  User::get('username');
        $data['app'] =  $this->app->name;
        $data['controller'] =  $this->name;
        $data['action'] =  $this->action;
        $data['title'] =  $title;
        $data['time'] =  time();
        $data['ip'] =  $_SERVER['REMOTE_ADDR'];

        $data['content'] =  serialize($content);
        $log->insert($data);
    
    }

    /**
     * 记录文件日志
     * @param string $type
     * @param string $file
     */

    protected function fileLog($type,$file,$info){
        $log = Cubox::app('admin')->model('UserFileLog');
        $data['user_id'] =  User::get('user_id');
        $data['app'] =  $this->app->name;
        $data['title'] = $info['title'];
        $data['size'] =  $info['size'];
        $data['ext'] = pathinfo($file,PATHINFO_EXTENSION);
        $data['type'] =  $type;
        $data['file'] =  $file;
        $data['time'] =  time();
        return $log->insert($data);
    }

    /**
     * 权限判断
     * @param string $power
     * @return boolean
     */
    protected function power($power,$return = false){
        if (User::power($power)) return true;
        if ($return) return false;
        else throw new \Exception('没有权限');
    }

    protected function plug($name){       
        return Cubox::plug($name,User::app());
    }

    protected function assetUrl($file){
        return Asset::url('/'.WEBPACK,$file);
    }
}